package com.example.apigateway.filter;

import org.springframework.stereotype.Component;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;


import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_ERROR_FILTER_ORDER;

/**
 * \* @author: bear
 * \* Date: 2022-04-08-14:29
 * \* describe: 限流
 */
@Component
public class RateLimitFilter extends ZuulFilter {
	private static final RateLimiter  RATE_LIMITER = RateLimiter.create(100);

	@Override
	public String filterType() {
		return PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return SEND_ERROR_FILTER_ORDER-1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		if(!RATE_LIMITER.tryAcquire()){
			throw new RuntimeException("xxxx");
		}
		return null;
	}
}
